//
//  LGHomeController.m
//  微博
//
//  Created by MS on 15-12-3.
//  Copyright (c) 2015年 MS. All rights reserved.
//

#import "LGHomeController.h"
#import "UIBarButtonItem+Item.h"
#import "LGTitleView.h"
#import "LGPopView.h"
#import "LGCover.h"
#import "LGOneController.h"
#import "LGAccountTool.h"
#import "LGAccount.h"
#import "LGStatus.h"
#import "MJExtension.h"
#import "LGUser.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "LGHttpTool.h"
#import "LGStatuesTool.h"
#import "LGUserTool.h"
#import "LGStutaesFrame.h"
#import "LGHomeCell.h"
@interface LGHomeController ()<LGCoverDelegate>
@property (nonatomic,weak) LGTitleView * titleView;
@property (nonatomic,strong) LGOneController * one;
/**
 *  statusesFrame -> LGStatuesFrame
 */
@property (nonatomic,strong) NSMutableArray * statusesFrame;

@end

@implementation LGHomeController

-(NSMutableArray *)statusesFrame
{
    if (_statusesFrame==nil) {
        
        _statusesFrame = [NSMutableArray array];
    }
    return _statusesFrame;
}

-(LGOneController *)one
{
    if (_one==nil) {
        
        _one = [[LGOneController alloc] init];
    }
    
    return _one;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavigationBar];
     self.tableView.backgroundColor =[UIColor colorWithRed:0.95f green:0.95f blue:0.95f alpha:1.00f];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //添加下拉刷新控件
    [self addUpRefresh];
    
    //请求当前用户的名称
    [LGUserTool  userNameWithSuccess:^(LGUser *user) {
        
        [self.titleView setTitle:user.name forState:UIControlStateNormal];
    
        //获取当前账号
       LGAccount * account = [LGAccountTool account];
        account.name = user.name;
        
        //保存当前用户名称
        [LGAccountTool saveAccount:account];
        
    } failure:^(NSError *error) {
        
    }];
}


-(void)addUpRefresh
{
    //添加下拉刷新控件
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewStates)];
    
    
    MJRefreshAutoNormalFooter * footView  = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreStates)];
    footView.automaticallyRefresh = NO;
    
    self.tableView.mj_footer  = footView;
    
    [self.tableView.mj_header beginRefreshing];

}

-(void)refresh
{
   
    [self.tableView.mj_header beginRefreshing];
   // [self loadNewStates];
}

-(void)loadMoreStates
{
    NSString * maxId = nil;
    LGStatus * s = [[self.statusesFrame lastObject] statues];
    long long maxID =[[s idstr] longLongValue]-1;
    if (self.statusesFrame.count) {
        maxId =[NSString stringWithFormat:@"%lld",maxID];
    }
    
    
    //把statues 转成statuesFrame
    NSMutableArray * sFrameTmpArr = [NSMutableArray array];
    [LGStatuesTool moreStatuesWithMaxID:maxId success:^(NSArray *statues) {
        
        [self.tableView.mj_footer endRefreshing];
        
        for (LGStatus * s in statues) {
            LGStutaesFrame * statuFrame = [[LGStutaesFrame alloc] init];
            statuFrame.statues = s;
            [sFrameTmpArr addObject:statuFrame];
        }
        
        [self.statusesFrame addObjectsFromArray:sFrameTmpArr];
        
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
    
}


-(void)loadNewStates
{
    NSString * sinceID = nil;
    if (self.statusesFrame.count) {
        LGStatus * s = [self.statusesFrame[0] statues];
        sinceID = [s idstr];
    }
    
    NSMutableArray * sFrameTmpArr = [NSMutableArray array];
    [LGStatuesTool newStatuesWithSinceID:sinceID success:^(NSArray *statues) {
        
        [self.tableView.mj_header endRefreshing];
        
        [self showNewCount:statues.count];
        
        for (LGStatus * s in statues) {
            LGStutaesFrame * statuFrame = [[LGStutaesFrame alloc] init];
            statuFrame.statues = s;
            [sFrameTmpArr addObject:statuFrame];
        }
        
        NSIndexSet * indexSet = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(0, statues.count)];
        
        
        //把最新的微博数插入到最前面
        [self.statusesFrame insertObjects:sFrameTmpArr atIndexes:indexSet];
        if (self.statusesFrame.count>20) {
            [self.statusesFrame removeObjectsInRange:NSMakeRange(20, self.statusesFrame.count-20)];
        }
        
        
        [self.tableView reloadData];
        
        
        
    } failure:^(NSError *error) {
        
    }];
    
}

#pragma mark 展示最新微博数
-(void) showNewCount:(NSInteger)count
{
    UILabel * label = [[UILabel alloc] init];
    
    CGFloat x = 0;
    CGFloat h = 35;
    CGFloat w = self.view.frame.size.width;
    CGFloat y = CGRectGetMaxY(self.navigationController.navigationBar.frame)-h;
    label.frame = CGRectMake(x, y, w, h);
    label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"timeline_new_status_background"]];
    label.text =[NSString stringWithFormat:@"最新微博数%ld",count];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    
    [UIView animateWithDuration:0.25 animations:^{
        label.transform = CGAffineTransformMakeTranslation(0, h);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.25 delay:2 options:UIViewAnimationOptionCurveLinear animations:^{
            label.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            
            [label removeFromSuperview];
        }];
        
    }];
    
}

-(void) setNavigationBar
{
    
    self.navigationItem.rightBarButtonItem =[UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"navigationbar_pop"] andHighImage:[UIImage imageNamed:@"navigationbar_pop_highlighted"] target:self action:@selector(btnRightClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"navigationbar_friendsearch"] andHighImage:[UIImage imageNamed:@"navigationbar_friendsearch_highlighted"] target:self action:@selector(addFriendClick:) forControlEvents:UIControlEventTouchUpInside];
    
  //  NSLog(@"%@",[LGAccountTool account].name);
    NSString * title = [LGAccountTool account].name? :@"首页";
    
    LGTitleView * btn = [LGTitleView buttonWithType:UIButtonTypeCustom];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateSelected];
    
    //高亮时不需要调整图片
    btn.adjustsImageWhenHighlighted = NO;
    
    [btn addTarget:self action:@selector(titleViewClick:) forControlEvents:UIControlEventTouchUpInside];
    self.titleView = btn;
    self.navigationItem.titleView = btn;
    
}



-(void) btnRightClick:(UIButton *)button
{
    
    //创建one
    //先找LGOne.xib-->LGOneController.xib-->自己创建近透明one
    //alloc init 底层调用initWithNibName: bundle:
    
    LGOneController * one = [[LGOneController alloc] init];
    
    //只会隐藏系统自带的tabBar
    one.hidesBottomBarWhenPushed =YES;
    
    [self.navigationController pushViewController:one animated:YES];
    
}

-(void) addFriendClick:(UIButton *)button
{
    
    // LGLog(@"%s",__func__);
}

-(void) titleViewClick:(UIButton *)button
{
    // LGLog(@"%s",__func__);
    _titleView.selected = !_titleView.selected;
    
    LGCover * cover = [LGCover show];
    cover.backgrondAlph = YES;
    cover.delegate = self;
    
    CGFloat popW = 200;
    CGFloat popX = (self.view.width - popW)* 0.5;
    CGFloat popH = popW;
    CGFloat popY = 55;
    LGPopView * popView = [LGPopView showInRect:CGRectMake(popX, popY, popW, popH)];
    
 
    popView.contenView = self.one.view;
}

-(void)coverDidClick:(LGCover *)cover
{
    [LGPopView hiddenView];
    
    _titleView.selected = NO;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.statusesFrame.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LGHomeCell * cell = [LGHomeCell cellWithTableView:tableView];
    
    //获取status模型
    LGStutaesFrame * statusFrame = self.statusesFrame[indexPath.row];
    cell.statusF = statusFrame;
    cell.backgroundColor =[UIColor clearColor];
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LGStutaesFrame * statusFrame = self.statusesFrame[indexPath.row];
    return statusFrame.cellHight;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
